using System.Collections.Generic;
using UnityEngine;

public class Trigger : MonoBehaviour
{   
    public Entity entity;
    
    /// <summary>
    /// 穿墙
    /// </summary>
    [Tooltip("是否可以穿墙检测")]
    public bool passWall;
    /// <summary>
    /// 检查的Tag
    /// </summary>
    [SerializeField]
    private List<string> checkTags = new List<string>();
    public bool TagCheck(string s){
        return checkTags.Contains(s);
    }
    
    /// <summary>
    /// 检查的实体Type
    /// </summary>
    [SerializeField]
    private List<EntityType> entityTypeEntityTypes = new List<EntityType>();
    public bool EntityTypeCheck(EntityType s){
        return entityTypeEntityTypes.Contains(s);
    }

    /// <summary>
    /// 检查的实体Tag
    /// </summary>
    [SerializeField]
    private List<EntityTag> ignoreEntityTags = new List<EntityTag>();
    public bool EntityTagCheck(List<EntityTag> s){
        return ignoreEntityTags.Exists(e => s.Contains(e));
    }
    
    /// <summary>
    /// 获取到的Object列表
    /// </summary>
    public List<GameObject> list = new List<GameObject>();
    private List<Entity> _entitys;
    public List<Entity> entitys{
        get{
            _entitys = new List<Entity>();
            foreach(GameObject o in list){
                Entity e = o.GetComponent<Entity>();
                if(e) _entitys.Add(e);
            }
            return _entitys;
        }
    }
    public Player targetPlayer{
        get{
            return entitys.Find(e => e.type == EntityType.Player) as Player;
        }
    }
    
    void Awake(){
        //忽略对本体实体的检测
        if(entity != null){
            if(entity.GetComponent<Collider2D>() != null){
                Physics2D.IgnoreCollision(entity.GetComponent<Collider2D>(), GetComponent<Collider2D>());
            }
        }
    }
    
    //获取实体
    void TriggerEntity(Entity e){
        if(EntityTypeCheck(e.type) && !EntityTagCheck(e.tags)){
            if(!list.Contains(e.gameObject)){
                list.Add(e.gameObject);
            }
        }
    }
    
    void OnTriggerEnter2D(Collider2D other){
        if(!passWall){
            RaycastHit2D hit = Physics2D.Linecast(other.transform.position, transform.position, 1<<LayerMask.NameToLayer("Wall"));
            if(hit.collider != null){
                return;
            }
        }
        if(TagCheck(other.tag)){
            Entity e = other.GetComponent<Entity>();
            if(e)TriggerEntity(e);
        }
    }
    
    void OnTriggerStay2D(Collider2D other){
        if(!passWall){
            RaycastHit2D hit = Physics2D.Linecast(other.transform.position, transform.position, 1<<LayerMask.NameToLayer("Wall"));
            if(hit.collider == null){
                OnTriggerEnter2D(other);
            }
        }
    }
    
    void OnTriggerExit2D(Collider2D other){
        if(list.Contains(other.gameObject)){
            list.Remove(other.gameObject);
        }
    }
    
}
